import time
import threading
import sys
import nls
from pydub import AudioSegment
from alitoken import create_token
import logging
import os
import random

# 全局日志格式配置
logging.basicConfig(
    stream=sys.stdout,
    level=logging.INFO,
    format="[%(asctime)s - %(module)s-%(lineno)s - %(thread)d - %(levelname)s] - %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S"
)

URL = "wss://nls-gateway-cn-shanghai.aliyuncs.com/ws/v1"

TMP_DIR = 'temp'
if not os.path.exists(TMP_DIR):
    os.makedirs(TMP_DIR)

def generate_random_string_custom(length=10):
    custom_char_set = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    random_string = ''.join(random.choice(custom_char_set) for i in range(length))
    return random_string

# 以下代码会根据上述TEXT文本反复进行语音合成
class TestTts:
    @staticmethod
    def synthesize_text(text):
        TOKEN = create_token()
        APPKEY = os.getenv('ALI_VOICE_APPKEY')
        random_name = generate_random_string_custom()
        pcm_file = os.path.join(TMP_DIR, random_name) + '.pcm'
        mp3_file = os.path.join(TMP_DIR, random_name) + '.mp3'

        event = threading.Event()

        class TtsInstance:
            def __init__(self):
                self.__f = open(pcm_file, "wb")
                self.__tts = nls.NlsSpeechSynthesizer(
                    url=URL,
                    token=TOKEN,
                    appkey=APPKEY,
                    on_metainfo=self.test_on_metainfo,
                    on_data=self.test_on_data,
                    on_completed=self.test_on_completed,
                    on_error=self.test_on_error,
                    on_close=self.test_on_close,
                    callback_args=[random_name]
                )
                self.__tts.start(text, voice="zhimiao_emo")

            def test_on_metainfo(self, message, *args):
                logging.debug("on_metainfo message=>{}".format(message))

            def test_on_data(self, data, *args):
                try:
                    self.__f.write(data)
                except Exception as e:
                    logging.debug("write data failed:", e)

            def test_on_completed(self, message, *args):
                logging.debug("on_completed:args=>{} message=>{}".format(args, message))

            def test_on_error(self, message, *args):
                logging.debug("on_error args=>{}".format(args))

            def test_on_close(self, *args):
                logging.debug("on_close: args=>{}".format(args))
                try:
                    self.__f.close()
                except Exception as e:
                    logging.debug("close file failed since:", e)
                # 读取PCM文件
                try:
                    audio = AudioSegment.from_file(pcm_file, format="raw", frame_rate=8000, channels=2, sample_width=2)
                    # 导出为MP3
                    audio.export(mp3_file, format="mp3")
                    #os.remove(pcm_file)
                except Exception as e:
                    logging.error("Conversion to MP3 failed: {}".format(e))
                finally:
                    event.set()

        tts_instance = TtsInstance()
        event.wait()
        return mp3_file


# 示例调用
if __name__ == "__main__":
    pass
